package com.syg.toolkit;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCKit {
    private static String url;
    private static String driver;
    private static String username;
    private static String password;

    /**
     * 1,相当于类的初始化(init)
     */
    static {
        try {
            //读取配置文件中数据库的连接信息
            InputStream is = JDBCKit.class.getClassLoader().getResourceAsStream("properties/srcConf.properties");
            Properties pro = new Properties();
            pro.load(is);
            url = pro.getProperty("jdbcUrl");
            driver = pro.getProperty("jdbcDriver");
            username = pro.getProperty("jdbcUsername");
            password = pro.getProperty("jdbcPassword");
            Class.forName(driver);//加载数据库驱动
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 2,不让外界创建对象
     */
    private JDBCKit() {
    }

    /**
     * 3,获取数据库的连接对象
     * @return 返回连接对象
     * @throws SQLException 声明方式处理异常
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,username,password);
    }

    /**
     * 释放资源
     * @param con:连接对象
     * @param st:执行sql语句的对象
     * @param rt:结果集对象
     * @throws SQLException 声明方式处理异常
     */
    public static void release(Connection con, Statement st, ResultSet rt) throws SQLException {
        if(con!=null){
            con.close();
        }
        if(st!=null){
            st.close();
        }
        if(rt!=null){
            rt.close();
        }
    }

    /**
     * 释放资源
     * @param objs :可变参数
     * @throws SQLException :声明方式处理异常
     */
    public static void releaseVariable(Object... objs) throws SQLException {
        for(Object obj:objs){
            if (obj instanceof Connection){
                System.out.println(obj.getClass()+">>>类型是connection");
                ((Connection) obj).close();
            }
            if(obj instanceof Statement){
                System.out.println(obj.getClass()+">>>类型是statement");
                ((Statement) obj).close();
            }
            if(obj instanceof ResultSet){
                System.out.println(obj.getClass()+">>>类型是resultset");
                ((ResultSet) obj).close();
            }
        }
    }
}
